package com.dounine.clouddisk360.parser;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONReader;
import com.alibaba.fastjson.JSONWriter;
import com.dounine.clouddisk360.exception.CloudDiskException;

public class JSONBianary {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(JSONBianary.class);
	
	private String bianaryPath;
	private String bianaryFilename;
	
	public <T> void writeObjToDisk(T obj){
		if(StringUtils.isNotBlank(bianaryPath)&&StringUtils.isNotBlank(bianaryFilename)){
			File file = new File(bianaryPath+bianaryFilename);
			if(!file.exists()){
				file.getParentFile().mkdirs();
			}
			JSONWriter jsonWriter = null;
			try {
				jsonWriter = new JSONWriter(new FileWriter(file));
				jsonWriter.startObject();
				jsonWriter.writeObject(obj);
				jsonWriter.endObject();
				jsonWriter.flush();
			} catch (IOException e) {
				e.printStackTrace();
			} finally{
				try {
					jsonWriter.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public <T> T readObjForDisk(Class<T> clazz){
		if(StringUtils.isNotBlank(bianaryPath)&&StringUtils.isNotBlank(bianaryFilename)){
			File file = new File(bianaryPath+bianaryFilename);
			if(!file.exists()){
				throw new CloudDiskException("读取的文件:[ "+bianaryFilename+" ]不存在");
			}
			JSONReader jsonReader = null;
			T t = null;
			try {
				jsonReader = new JSONReader(new FileReader(file));
				jsonReader.startObject();
				t = jsonReader.readObject(clazz);
				jsonReader.endObject();
				LOGGER.info("[ "+bianaryFilename+ " ]文件保存位置:"+bianaryPath);
			} catch (IOException e) {
				e.printStackTrace();
			} finally{
				jsonReader.close();
			}
			return t;
		}
		throw new CloudDiskException("读取的对象的文件位置与文件名不能为空");
	}
	
	public <T> void writeListToDisk(List<T> lists){
		
	}
	
	public <T> List<T> readListForDisk(List<T> lists,Class<T> clzz){
		return null;
	}

	public void setBianaryPath(String bianaryPath) {
		this.bianaryPath = bianaryPath;
	}

	public void setBianaryFilename(String bianaryFilename) {
		this.bianaryFilename = bianaryFilename;
	}
	
	

}
